import { useState, useEffect, useRef } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import http from "../utils/http"; // 使用http工具
import styles from "./payment.module.css";
import axios from "axios";

const Payment = () => {
  const [paymentMethod, setPaymentMethod] = useState("alipay"); // 默认选择支付宝支付
  const [orderData, setOrderData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [rawResponse, setRawResponse] = useState(null); // 保存原始响应用于调试
  const [nightsCount, setNightsCount] = useState(1); // 默认入住1晚
  const alipayForm = useRef(null);
  const location = useLocation();
  const navigate = useNavigate();

  // 解析URL参数获取ID
  const queryParams = new URLSearchParams(location.search);
  const _id = queryParams.get('id');

  // 获取订单数据
  useEffect(() => {
    const fetchData = async () => {
      if (!_id) {
        setError("未提供有效的订单ID");
        setLoading(false);
        return;
      }

      try {
        setLoading(true);
        setError(null);

        // 发送API请求获取数据
        const requestUrl = `/searcid/?_id=${_id}`;
        console.log("发送请求:", requestUrl);

        const res = await http.get(requestUrl);
        console.log("API返回的完整响应:", res);
        console.log("API返回的数据:", res.data);

        // 保存原始响应用于调试
        setRawResponse(res.data);

        // 处理API返回的数据 - 基于实际提供的JSON结构
        if (res.data && res.data.code === 200) {
          // 使用正确的数据路径
          const hotelData = res.data.list;

          if (hotelData) {
            // 设置最大可选天数
            const maxNights = hotelData.day || 7;

            // 构建订单数据对象
            const formattedData = {
              orderInfo: {
                roomNumber: hotelData.room || "暂无房间信息",
                hotelName: hotelData.hname || "未知酒店", // 使用hname作为酒店名称
                customer: hotelData.name || "暂无客人信息",
                phone: hotelData.phone || "暂无电话号码",
              },
              payment: {
                total: calculateTotal(hotelData.price, 1), // 初始默认1晚
                roomPrice: hotelData.price || 0,
                memberDiscount: calculateDiscount(hotelData.price, 1), // 初始默认1晚
                coupon: 3, // 默认优惠券额度
                pricePerNight: hotelData.price || 0,
                maxNights: maxNights
              },
              stayInfo: {
                dateRange: formatDate(hotelData.start) && formatDate(hotelData.end) ?
                  `${formatDate(hotelData.start)} - ${formatDate(hotelData.end)}` : "暂无日期信息",
                roomType: hotelData.room || "标准房"
              }
            };

            setOrderData(formattedData);
          } else {
            setError("返回的数据结构中没有找到房间信息");
          }
        } else {
          setError(`API返回错误: ${res.data?.message || '未知错误'}`);
        }
      } catch (err) {
        console.error("获取数据失败:", err);
        setError(err.message || "获取订单数据失败，请检查网络连接");
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [_id]);

  // 计算折扣价格（示例：会员卡65折）
  const calculateDiscount = (price, nights = 1) => {
    if (!price) return 0;
    return parseFloat((price * nights * 0.35).toFixed(1)); // 会员卡折扣35%
  };

  // 计算总价
  const calculateTotal = (price, nights = 1) => {
    if (!price) return 0;
    const discount = calculateDiscount(price, nights);
    const coupon = 3;
    return parseFloat((price * nights - discount - coupon).toFixed(1));
  };

  // 更新夜数和价格
  const updateNightsCount = (newCount) => {
    if (!orderData) return;

    // 确保夜数在有效范围内
    const maxNights = orderData.payment.maxNights;
    const validCount = Math.max(1, Math.min(newCount, maxNights));

    setNightsCount(validCount);

    // 更新订单数据中的价格
    const updatedOrderData = {
      ...orderData,
      payment: {
        ...orderData.payment,
        total: calculateTotal(orderData.payment.pricePerNight, validCount),
        memberDiscount: calculateDiscount(orderData.payment.pricePerNight, validCount),
        roomPrice: orderData.payment.pricePerNight * validCount
      }
    };

    setOrderData(updatedOrderData);
  };

  // 格式化日期
  const formatDate = (dateString) => {
    if (!dateString) return "";

    try {
      const date = new Date(dateString);
      if (isNaN(date.getTime())) {
        return dateString;
      }

      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');

      return `${month}-${day}`;
    } catch (e) {
      console.error("日期格式化错误:", e);
      return dateString;
    }
  };

  const handlePaymentMethodChange = (method) => {
    setPaymentMethod(method);
  };

  const handleSubmitPayment = async () => {
    try {
      console.log("提交续住请求, ID:", _id, "续住天数:", nightsCount);

      // 准备要发送的数据 - 只包含必要的信息
      const updateData = {
        _id: _id,
        nights: nightsCount // 续住的天数
      };

      // 调用后端更新接口
      const response = await http.post("/update", updateData);

      if (response.data && response.data.code === 200) {
        // router('/Extension');  // 使用已定义的router进行导航
      } else {
        alert("续住操作失败，请重试");
      }
    } catch (error) {
      console.error("续住请求失败:", error);
      alert("系统错误，请稍后再试");
    }

    let res = await axios.post('http://localhost:3010/alipay', { price: orderData.payment.total, name: "酒店续住" });

    alipayForm.current.innerHTML = res.data;
    // 主动调用form表单
    // document.forms 获取当前页面所有的表单集合
    document.forms[0].submit();
  };

  // 显示加载中
  if (loading) {
    return (
      <div className={styles.paymentContainer}>
        <div className={styles.header}>
          <button className={styles.backButton} onClick={() => navigate(-1)}>
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white" width="28" height="28">
              <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z" />
            </svg>
          </button>
          <h1 className={styles.title}>续住操作</h1>
        </div>
        <div className={styles.loading}>
          <div className={styles.spinner}></div>
          <p>加载中...</p>
        </div>
      </div>
    );
  }

  // 显示错误信息
  if (error || !orderData) {
    return (
      <div className={styles.paymentContainer}>
        <div className={styles.header}>
          <button className={styles.backButton} onClick={() => navigate(-1)}>
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white" width="28" height="28">
              <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z" />
            </svg>
          </button>
          <h1 className={styles.title}>续住操作</h1>
        </div>
        <div className={styles.errorContainer}>
          <div className={styles.errorIcon}>❌</div>
          <p className={styles.errorMessage}>{error || "无法加载订单数据"}</p>
          <p className={styles.errorDetail}>订单ID: {_id || "未提供"}</p>

          {/* 显示原始响应数据用于调试 */}
          {rawResponse && (
            <div className={styles.rawDataSection}>
              <h4>API返回数据:</h4>
              <pre className={styles.rawDataDisplay}>
                {JSON.stringify(rawResponse, null, 2)}
              </pre>
            </div>
          )}

          <button className={styles.retryButton} onClick={() => window.location.reload()}>
            重试
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className={styles.paymentContainer}>
      <div ref={alipayForm} style={{ display: 'none' }}>form表单</div>
      <div className={styles.header}>
        <button className={styles.backButton} onClick={() => navigate(-1)}>
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white" width="28" height="28">
            <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z" />
          </svg>
        </button>
        <h1 className={styles.title}>续住操作</h1>
        <div className={styles.headerRight}>
          <button className={styles.helpButton}>
            <i className={styles.helpIcon}></i>
          </button>
        </div>
      </div>

      <div className={styles.orderInfo}>
        <div className={styles.orderTitle}>
          {orderData.orderInfo.roomNumber} | {orderData.orderInfo.hotelName}
        </div>

        <div className={styles.customerInfo}>
          <div className={styles.infoItem}>
            <span className={styles.label}>在住客人:</span>
            <span className={styles.value}>{orderData.orderInfo.customer}</span>
          </div>
          <div className={styles.infoItem}>
            <span className={styles.label}>手机号码:</span>
            <span className={styles.value}>{orderData.orderInfo.phone}</span>
          </div>
        </div>
      </div>

      {/* 选择入住天数 */}
      <div className={styles.nightsSelector}>
        <h3 className={styles.sectionTitle}>选择入住天数</h3>

        <div className={styles.nightsControl}>
          <button
            className={styles.nightsButton}
            onClick={() => updateNightsCount(nightsCount - 1)}
            disabled={nightsCount <= 1}
          >
            -
          </button>

          <div className={styles.nightsDisplay}>
            <span className={styles.nightsCount}>{nightsCount}</span>
            <span className={styles.nightsLabel}>晚</span>
          </div>

          <button
            className={styles.nightsButton}
            onClick={() => updateNightsCount(nightsCount + 1)}
            disabled={nightsCount >= orderData.payment.maxNights}
          >
            +
          </button>
        </div>

        <div className={styles.nightsInfo}>
          <span>最多可续住 {orderData.payment.maxNights} 晚</span>
        </div>
      </div>

      <div className={styles.paymentMethods}>
        <h3 className={styles.sectionTitle}>支付信息</h3>

        <div className={styles.methodOptions}>
          <div
            className={`${styles.methodOption} ${paymentMethod === 'alipay' ? styles.selected : ''}`}
            onClick={() => handlePaymentMethodChange('alipay')}
          >
            <div className={styles.methodIcon}>💙</div>
            <div className={styles.methodName}>支付宝支付</div>
            <div className={styles.methodDesc}>快捷 | 安全 | 便利</div>
          </div>

          <div
            className={`${styles.methodOption} ${paymentMethod === 'wechat' ? styles.selected : ''}`}
            onClick={() => handlePaymentMethodChange('wechat')}
          >
            <div className={styles.methodIcon}>💬</div>
            <div className={styles.methodName}>微信支付</div>
            <div className={styles.methodDesc}>押金预授权自动退款</div>
          </div>
        </div>
      </div>

      <div className={styles.priceDetails}>
        <h3 className={styles.sectionTitle}>费用明细</h3>

        <div className={styles.priceItem}>
          <span className={styles.itemName}>支付宝支付</span>
          <span className={styles.itemPrice}>¥{orderData.payment.total}</span>
        </div>

        <div className={styles.priceItem}>
          <span className={styles.itemName}>
            {orderData.stayInfo.roomType} {nightsCount}晚 ({orderData.payment.pricePerNight}元/晚)
          </span>
          <span className={styles.itemPrice}>¥{orderData.payment.roomPrice}</span>
        </div>

        <div className={styles.priceItem}>
          <span className={styles.itemName}>超级会员价65折</span>
          <span className={styles.itemPrice}>-¥{orderData.payment.memberDiscount}</span>
        </div>

        <div className={styles.priceItem}>
          <span className={styles.itemName}>优惠券</span>
          <span className={styles.itemPrice}>-¥{orderData.payment.coupon}</span>
        </div>
      </div>

      <div className={styles.totalSection}>
        <div className={styles.totalPrice}>
          <span>合计:</span>
          <span className={styles.totalAmount}>¥{orderData.payment.total}</span>
        </div>
        <button
          className={styles.paymentButton}
          onClick={handleSubmitPayment}
        >
          立即支付
        </button>
      </div>
    </div>
  );
};

export default Payment;